package com.thinkfit.jy.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.common.lib.constant.Constants;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.mvp.contract.EmptyContract;
import com.common.lib.mvp.presenter.EmptyPresenter;
import com.common.lib.utils.LogUtil;
import com.thinkfit.jy.R;
import com.thinkfit.jy.bean.WifiBean;
import com.thinkfit.jy.utils.WifiSupport;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 输入wifi密码界面
 */
public class InputWifiPswFragment extends BaseFragment<EmptyContract.Presenter> implements EmptyContract.View {

    private WifiBean mWifiBean;

    @NonNull
    @Override
    protected EmptyContract.Presenter onCreatePresenter() {
        return new EmptyPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_input_wifi_psw;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        setViewsOnClickListener(R.id.tvBack, R.id.tvConnect);
        mWifiBean = (WifiBean) getArguments().getSerializable(Constants.BUNDLE_EXTRA);
        EditText etPsw = view.findViewById(R.id.etPsw);
        etPsw.setHint(getString(R.string.app_input_xxx_wifi_psw, mWifiBean.getWifiName()));
        TextView tvConnect = view.findViewById(R.id.tvConnect);
        tvConnect.setEnabled(false);
        etPsw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() > 7) {
                    tvConnect.setBackgroundResource(R.drawable.shape_ffffff_5);
                    tvConnect.setTextColor(ContextCompat.getColor(getActivity(), com.common.lib.R.color.color_21_20_20));
                    tvConnect.setEnabled(true);
                } else {
                    tvConnect.setBackgroundResource(R.drawable.shape_2bffffff_5);
                    tvConnect.setTextColor(ContextCompat.getColor(getActivity(), com.common.lib.R.color.color_2b_fe_fe_fe));
                    tvConnect.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvBack:
                getParentFragmentManager().popBackStack();
                break;
            case R.id.tvConnect:
                WifiInfo wifiInfo = WifiSupport.getConnectedWifiInfo(getActivity());
                if (wifiInfo != null) {
                    WifiSupport.doDisconnectWifi(wifiInfo.getSSID(), getActivity());
                }
                String psw = getTextById(R.id.etPsw);
                WifiConfiguration wifiConfiguration = WifiSupport.createWifiConfig(mWifiBean.getWifiName(), psw, WifiSupport.getWifiCipher(mWifiBean.getCapabilities()));
                WifiSupport.addNetWork(wifiConfiguration, getActivity());
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBroadcastReceive(Intent intent) {
        if (getView() == null) {
            return;
        }
        if(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())){   //密码监听
            SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
            NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(supplicantState);
            int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
            LogUtil.LogE("当前网络连接状态码：" + error + "；连接状态 --->>> " + state);
            if (error == WifiManager.ERROR_AUTHENTICATING) {
                String ssidName = ((WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getSSID();
                LogUtil.LogE( ssidName + "：密码错误，连接状态 --->>>" + state +"，connectType：");
                //状态为 DISCONNECTED 断开的 时候才是真的密码错误
                if(state == NetworkInfo.DetailedState.DISCONNECTED){
                    showToast("密码错误，连接失败");
                    //用系统自己的方式忘记wifi
                   // boolean b = WifiSupport.forgetWifiNetWork(ssidName, mContext);//连接失败后需要忘记密码，不然会因为重连机制导致反复广播
                    //密码错误时清空保持中的密码
                    //PreferenceHelper.write(mContext,ssidName,"");
                }else if(state == NetworkInfo.DetailedState.SCANNING){
                    //密码正确的时，第一次会走密码错误的逻辑 进入 SCANNING 扫描的状态，或者进入 CONNECTING 连接的状态

                }
            }
        }

    }
}